import 'package:flutter_jd/tools/utils/storage.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

class SearchController extends GetxController {
  // final historyList = [].obs; // 搜索历史

  final historyList = RxList<String>([]); // 搜索历史
  // 默认数据
  final defaultList = RxList<String>([
    'MacBook Pro',
    'iPhone12',
    '机械键盘',
    '手机',
    '笔记本电脑',
    '显示器',
    '洗发水',
    '吹风机',
    '水杯',
  ]);

  final isDelete = false.obs;

  @override
  void onInit() {
    super.onInit();
    initSearchHistory();
  }

  // 初始化搜索记录
  initSearchHistory() {
    List<String> list = StorageUtil().getStringList('searchHistory') ?? [];

    if (list.length > 0) {
      historyList.insertAll(0, list);
    } else {
      historyList.value = defaultList;
    }
  }

  // 搜索
  search(value) {
    if (value.toString().isNotEmpty) {
      historyList.insert(0, value);
      saveStorage();
    }
  }

  openDelete() {
    isDelete.value = !isDelete.value;
  }

  deleteItem(int index) {
    historyList.removeAt(index);
    saveStorage();
  }

  clearAll() {
    historyList.clear();
    saveStorage();
  }

  saveStorage() {
    StorageUtil().setStringList('searchHistory', historyList);
  }
}
